package com.web_bloks.http.client;

import com.web_bloks.system.client.Logger;

import com.google.gwt.user.client.Timer;

/**
 * HttpTransaction
 * Simple HTTP transaction class. Headers can't be set.
 * 
 * @author Jean-Lou Dupont
 *
 */
abstract public class HttpTransaction implements ResponseTextHandlerEx {

	final public static int GET = 0;
	final public static int POST = 1;
	
	protected ResponseTextHandlerEx handler = null;
	
	protected boolean busy      = false;
	protected boolean completed = false;

	protected String data = null;
	
	/*===================================================================
	 * CONSTRUCTORS 
	 ===================================================================*/
	
	public HttpTransaction( ) {
	}
	
	/*===================================================================
	 * PUBLIC 
	 ===================================================================*/
	public void setData(String data) {
		this.data = data;
	}
	public void setHandler(ResponseTextHandlerEx h) {
		handler = h;
	}
	
	public boolean isBusy() {
		return busy;
	}
	/**
	 * Executes the transaction
	 * 
	 * @param url String
	 * @param timeout int
	 * @return result boolean 
	 * @throws HttpTransactionException
	 */
	@SuppressWarnings("deprecation")
	public boolean execute(int type, String url, int timeout) 
		throws HttpTransactionException {

		beginTransaction(type, url, timeout);
		
		//just for the logger's benefit
		final String _u = url;
		
		if (busy)
			return false;
		
		Timer t = new Timer() {
			public void run() {
				busy = false;
				if (!completed) {
					Logger.logError("HtmlRegionLoader.Load: failed to load url["+_u+"]");
					onTimeout();
				}
			}
		};
		
		boolean response;

		switch(type) {
		case GET: 
			response = com.google.gwt.user.client.HTTPRequest.asyncGet(url, this);
			break;
		case POST:
			response = com.google.gwt.user.client.HTTPRequest.asyncPost(url, data, this);
			break;
		default:
			throw new HttpTransactionException();
		}
		
		completed = false;
		busy = true;
		t.schedule(timeout);
		
		endTransaction();
		
		return response;
	}//
	
	public void onCompletion(String responseText) {
		completed = true;
		if (handler != null)
			handler.onCompletion(responseText);
	}
	public void onTimeout() {
		completed = true;
		if (handler != null)
			handler.onTimeout();
	}
	/*===================================================================
	 * TEMPLATE METHODS 
	 ===================================================================*/

	abstract protected void beginTransaction(int type, String url, int timeout);
	abstract protected void endTransaction();
	
}//END
